package com.imooc.service.impl;

import com.imooc.dto.OrderDTO;
import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;
import com.imooc.service.BuyerOrderService;
import com.imooc.service.OrderMasterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author liuhuan
 * @date 2018/7/8 09:49
 * @description
 */
@Service
@Slf4j
public class BuyerOrderServiceImpl implements BuyerOrderService {

    @Autowired
    private OrderMasterService orderMasterService;

    @Override
    public OrderDTO findOneOrder(String openId, String orderId) {



        return checkOpenId(openId,orderId);
    }

    @Override
    public OrderDTO cancelOrder(String openId, String orderId) {
        OrderDTO orderDTO=checkOpenId(openId,orderId);
        if(orderDTO==null){
            log.error("【取消订单】订单不存在，orderDTO={}",orderDTO);
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderDTO;
    }

    /**
     * check openid
     * @param openId
     * @param orderId
     * @return
     */
    private OrderDTO checkOpenId(String openId, String orderId){
        OrderDTO orderDTO=orderMasterService.findOne(orderId);
        if(orderDTO==null){
            return null;
        }
        if(!Objects.equals(orderDTO.getOrderId(),openId)){
            log.error("【查询订单详情】openid不一致，openId={},orderDTO.getOrderId()={}",openId,orderDTO.getOrderId());
            throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
